<template>
  <view class="userInfoPage">
    <view class="content">
      <uni-card class="card" is-shadow :isFull="true" :title="loginUser.userAccount"
                :extra="isLogin ? '已登录': '未登录' "
                :thumbnail="loginUser.userAvatar">

        <text>用户名：{{ loginUser.userName }}</text>
        <br/>
        <text>角色：{{ loginUser.userRole == undefined ? '' : (loginUser.userRole == 'admin' ? '管理员' : '用户') }}
        </text>
        <br/>
        <text>性别：{{ loginUser.gender == undefined ? '' : (loginUser.gender == 0 ? '女' : '男') }}</text>
        <br/>
        <text>邮箱：{{ loginUser.email }}</text>
        <br/>
        <text>电话：{{ loginUser.phone }}</text>
      </uni-card>
    </view>
    <view class="footer">
      <button type="primary" @click="handleLogin">{{ isLogin ? '退出' : '登录' }}</button>
      <button @click="handleBack">返回</button>
    </view>
  </view>
</template>

<script setup lang="ts">
import {effect, onBeforeUnmount, onMounted, ref} from 'vue'
import {getCurrentUserUsingGet, userLogoutUsingPost} from "@/services/api/sysUserController";
import {LOGIN_EVENT, LOGOUT_EVENT} from "@/constants/sysConstants";
import {onLoad, onUnload} from "@dcloudio/uni-app";

const defaultUser = {
  userAccount: "游客",
  userAvatar: "../../static/logo.png",
  email: "",
  gender: undefined,
  phone: "",
  userName: "",
  userRole: undefined
}

const loginUser = ref<API.SysUser>({...defaultUser});
const isLogin = ref<boolean>(false);

const initData = () => {
  isLogin.value = false;
  loginUser.value = {...defaultUser};
}

const handleLogin = async () => {
  if (isLogin.value) {
    await userLogoutUsingPost();
    initData();
  } else {
    uni.navigateTo({
      url: "/pages/login/index"
    })
  }
}

const handleBack = () => {
  uni.switchTab({
    url: "/pages/me/index"
  })
}

const loadData = async () => {
  const data = await getCurrentUserUsingGet();
  if (data) {
    loginUser.value = data as API.SysUser;
    isLogin.value = true;
  } else {
    initData();
  }
}

const initEvent = () => {
  uni.$on(LOGIN_EVENT, () => {
    loadData();
  })
  uni.$on(LOGOUT_EVENT, () => {
    initData();
  })
}

onLoad(() => {
  initEvent();
})

onUnload(() => {
  uni.$off(LOGIN_EVENT);
  uni.$off(LOGOUT_EVENT);
});

effect(() => {
  loadData();
}, {})

</script>

<style scoped>
.userInfoPage {
  //display: flex;
  //flex-direction: column;
  //align-items: center;
  //justify-content: center;
  min-height: 100vh;
  //padding-bottom: 50px; /* 留出底部空间 */
  //width: 100%;
  //height: 100vh;
  background: linear-gradient(to right, #ebf1fd, #ffffff);

  .content {
    padding: 5px;
    width: 100%;

    .card {
      background: linear-gradient(to right, #ebf1fd, #ffffff);

    }
  }

  .footer {
    position: absolute;
    bottom: 0;
    width: 100%;
    padding: 10px 0; /* 底部内边距 */
    text-align: center; /* 底部内容居中 */
  }

  .footer button {
    margin: 10px 5px; /* 按钮上下间距 */
  }
}

</style>
